package io.rocketman.transport.netty.server.handler;


import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import io.netty.util.CharsetUtil;
import io.rocketman.transport.channel.Channel;
import io.rocketman.transport.channel.ChannelConvertor;
import io.rocketman.transport.channel.handler.ChannelHandler;
import io.rocketman.transport.netty.channel.NettyChannel;
import io.rocketman.transport.netty.channel.NettyChannelConvertor;
import io.rocketman.transport.server.handler.ServerChannelHandler;

import java.net.InetSocketAddress;


/**
 * @author He Peng
 * @create 2018-05-25 3:19
 * @update 2018-05-25 3:19
 * @updatedesc : 更新说明
 * @see
 */
public class NettyServerChannelHandler extends ChannelHandlerAdapter {

    private static final ChannelConvertor channelConvertor = new NettyChannelConvertor();
    private ChannelHandler channelHandler;

    public NettyServerChannelHandler(ChannelHandler channelHandler) {
        this.channelHandler = channelHandler;
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf byteBuf = (ByteBuf) msg;
        System.out.println("Server Clients Msg : " + byteBuf.toString(CharsetUtil.UTF_8));

        // TODO 封装 Channel , 把 msg 处理成 rocketman 可以理解的类型
        io.netty.channel.Channel nChannel = ctx.channel();
        Channel channel = channelConvertor.convert(nChannel);

        // TODO ServerChannelHandler 用代理模式封装 , 处理 协议头解析 、 编解码 、 序列化
        this.channelHandler.received(channel , msg);
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        System.out.println("Server Read Msg : " + ctx);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        System.out.println("exceptionCaught : " + ctx);
    }
}

